package com.shj.web.security.handler;

import com.shj.model.ResResult;
import com.shj.web.config.JwtConfig;
import com.shj.web.security.entity.SelfUserEntity;
import com.shj.web.util.JwtTokenUtil;
import com.shj.web.util.ResultUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO 登录成功处理类
 * @Author songhuajian
 * @Date 2020/3/13 0:00
 **/
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SelfUserEntity selfUserEntity = (SelfUserEntity) authentication.getPrincipal();
        String token = JwtTokenUtil.createAccessToken(selfUserEntity);
        token = JwtConfig.tokenPrefix + token;

        Map<String, String> data = new HashMap<>();
        data.put("token", token);

        // 返回前端
        ResResult result = new ResResult();
        result.setCode(200);
        result.setMsg("SUCCESS");
        result.setData(data);
        ResultUtil.responseJson(response, result);
    }
}
